package com.yanqu.road.server.cmd.marriage.cross;

import com.yanqu.road.pb.marriage.CrossMarriageProto;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.cmd.base.AbstractCommand;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.manger.CrossMarriageGroupMgr;
import com.yanqu.road.server.manger.marriage.MarriageMgr;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.string.StringUtils;

import java.math.BigInteger;

@Cmd(code = Protocol.S_CROSS_MARRIAGE_APPLY_PUBLISH, desc = "跨服发布联姻请求")
public class CrossMarriageApplyPublishCmd extends AbstractCommand {

    private String childUid;
    private BigInteger limitEarnSpeed = BigInteger.ZERO;
    private long appointUserId;
    private long partnerServerId;

    @Override
    public boolean parseData(YanQuMessage packet) throws Exception {
        CrossMarriageProto.CrossMarriageApplyPublishReqMsg reqMsg = CrossMarriageProto.CrossMarriageApplyPublishReqMsg.parseFrom(packet.getBytes());
        childUid = reqMsg.getChildUid();
        String value = reqMsg.getLimitEarnSpeed();
        if(!StringUtils.isNullOrEmpty(value)){
            limitEarnSpeed = new BigInteger(value);
        }
        appointUserId = reqMsg.getAppointUserId();
        partnerServerId = reqMsg.getPartnerServerId();
        return true;
    }

    @Override
    public void execute(GamePlayer player, YanQuMessage packet) throws Exception {
        if(!CrossMarriageGroupMgr.canCrossMarriage(GameServer.getInstance().getServerId())){
            ret = GameErrorCode.E_CROSS_MARRIAGE_NO_OPEN;
            return;
        }
        if(appointUserId > 0){
            if(partnerServerId == GameServer.getInstance().getServerId()){
                ret = GameErrorCode.E_CROSS_MARRIAGE_SERVER_NO_SAME;
                return;
            }
            if(appointUserId == player.getUserId()) {
                ret = GameErrorCode.E_MARRIAGE_NO_SELF;
                return;
            }
        }
        ret = MarriageMgr.publishCrossMarriageApply(player, childUid, limitEarnSpeed, appointUserId, partnerServerId);
    }

    @Override
    public void sendData(GamePlayer player) {
        if(0 != ret) {
            CrossMarriageProto.CrossMarriageApplyPublishRespMsg.Builder respMsg = CrossMarriageProto.CrossMarriageApplyPublishRespMsg.newBuilder();
            respMsg.setRet(ret);
            player.sendPacket(Protocol.U_CROSS_MARRIAGE_APPLY_PUBLISH, respMsg);
        }
    }
}
